package com.cfuture08.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectUtil {
	private Object object;

	public void setObject(Object object) {
		this.object = object;
	}

	public Object getObject() {
		return this.object;
	}

	public ReflectUtil(Object object) {
		this.object = object;
	}

	public ReflectUtil() {
	}
	
	public ReflectUtil(Class<?> clazz) throws InstantiationException, IllegalAccessException {
		this.object = clazz.newInstance();
	}

	public String getSimpleName() {
		return this.object.getClass().getSimpleName();
	}

	public String getName() {
		return this.object.getClass().getName();
	}

	public String[] getFieldsName() {
		Field[] fields = this.getFields();
		String[] result = null;
		if (fields != null) {
			result = new String[fields.length];
			for (int i = 0; i < result.length; ++i) {
				result[i] = fields[i].getName();
			}
		}

		return result;
	}

	/**
	 * 取得所有声明过的属性
	 * 
	 * @return
	 */
	public Field[] getFields() {
		return this.object.getClass().getDeclaredFields();
	}

	/**
	 * 取得跟输入名字相符的方法实例
	 * 
	 * @param name
	 * @param t
	 * @return
	 */
	public Method getMethod(String name) {
		Method result = null;
		try {
			Method[] ms = this.object.getClass().getDeclaredMethods();
			for (Method m : ms) {
				if (name.equals(m.getName())) {
					result = m;
					break;
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 取得跟输入名字相符的属性实例
	 * 
	 * @param name
	 * @param t
	 * @return
	 */
	public Field getField(String name) {
		Field result = null;
		try {
			Field[] fs = this.object.getClass().getDeclaredFields();
			for (Field f : fs) {
				if (name.equals(f.getName())) {
					result = f;
					break;
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 去的所有声明的方法
	 * 
	 * @return
	 */
	public Method[] getMethods() {
		return this.object.getClass().getDeclaredMethods();
	}
}
